import { Meteor } from "meteor/meteor";
import { check } from 'meteor/check';
import axios from "axios";
import { successResponse, errorResponse, getErpAccessToken, generateExternalCode } from "./baseCollection.js";
const { sutando } = require("sutando");
const config = require("../config/db.js");
sutando.addConnection(config.mysql);
sutando.addConnection(config.mssql, "sqlserver");
const db = sutando.connection();
const sqlserverDb = sutando.connection("sqlserver");

Meteor.methods({

  //获取易买存货
  async getYimInventory() {
    try {
      // 模拟从数据库查询用户
      const user = await db.table("ym_inventory").get();
      //console.log(user);
      if (!user || user.length === 0) {
        return errorResponse("用户不存在或查询结果为空");
      }
      // 返回成功的响应
      return successResponse(user);
    } catch (error) {
      // 捕获错误并返回标准的错误响应
      return errorResponse(error.message, 500);
    }
  },


  //下采购订单
  async createPurchaseOrder() {
    const jsonData = {
      "purchaseOrderDTO": {
        "VoucherDate": new Date().toISOString().split("T")[0],//单据日期
        "ExternalCode": generateExternalCode(),//外部单据号
        "Partner": {
          "Code": "001"//供应商编码
        },
        "BusinessType": {
          "Code": "01"//业务类型
        },
        "Memo": "测试测试",//备注
        "VoucherDetails": [{
          "Inventory": {
            "Code": "A1"//存货编码
          },
          "Quantity": 1,//数量
          "OrigDiscountPrice": 200//原始单价
        }
        ]
      }
    };
    //console.log(jsonData);
    //return;
    const url = "https://openapi.chanjet.com/tplus/api/v2/purchaseOrder/Create";
    const headers = {
      openToken: await getErpAccessToken(),
      appKey: 'm94TDXsa',
      appSecret: 'BEAE0F1482C84C041BC8F8B12775047C',
      'Content-Type': 'application/json',
    };
    //console.log(headers);return
    try {
      const response = await axios.post(url, jsonData, { headers });
      console.log('请求成功:', response.data);
      return response.data;
    } catch (error) {
      console.error('请求出错:', error);
      throw error;
    }
  },

  //存货上传
  async createInventory(selectRecords) {
    check(selectRecords, Array); // 确保 selectRecords 是数组
    for (const record of selectRecords) {
      const isCode = sqlserverDb.table("ym_inventory").where({ inventory_code: record.inventory_code }).first();
      if (!isCode) {
        const jsonData = {
          dto: {
            Code: record.inventory_code,
            Name: record.inventory_name,
            DefaultBarCode: record.specification,
            Disabled: false,
            IsPurchase: true,
            IsSale: true,
            IsMadeSelf: true,
            IsMaterial: true,
            IsLaborCost: false,
            Unit: {
              Name: record.unit,
            },
            Brand: {
              Name: record.brand,
            },
            InventoryClass: {
              Code: "0307",
              Name: "订购件"
            },
            ValueType: {
              Code: "01"
            }
          }
        };

        const url = `http://192.168.10.111:11000/ScOrderW/InventoryAdd111111?JsonData=${encodeURIComponent(JSON.stringify(jsonData))}`;
        try {
          const response = await axios.get(url);
          if (response.data.code !== 1) {
            console.error('请求失败:', response.data);
            break; // 终止后续请求
          }
          console.log('请求成功:', response.data);
        } catch (error) {
          console.error('请求错误:', error);
          break; // 终止后续请求
        }
      }
    }
  },

  //更新存货
  async saveYimInventory(insertRecords, updateRecords) {
    check(insertRecords, Array);
    check(updateRecords, Array);
    if (insertRecords.length > 0) {
      for (const record of insertRecords) {
        delete record._X_ROW_KEY;
        delete record.action;
        delete record.name;
        if (!record.inventory_code) {
          return errorResponse("存货编码不能为空!");
        }
      }
      const isRes = db.table("ym_inventory").insert(insertRecords);
      if (isRes>0) {
        return successResponse([],"插入成功!"); 
      }else{
        return errorResponse("插入失败!"); 
      }
    }
  
    if (updateRecords.length > 0) {
      for (const record of updateRecords) {
        delete record._X_ROW_KEY;
        const isRes = await db.table("ym_inventory").where({ id: record.id }).update(record);
        if (isRes > 0) {
          return successResponse([],"更新成功!");
        } else {
          return errorResponse("更新失败!");
        }
      } 
    }

},
});
